import { createRouter, createWebHistory } from 'vue-router'
import Oauth2Authorize from '@/views/Oauth2Authorize.vue'
import Home from '@/views/Home.vue'
import Course from '@/views/Course.vue'
import Profile from '@/views/Profile.vue'
import Complain from '@/views/Complain.vue'
import AddComplain from '@/views/AddComplain.vue'
import BankCard from '@/views/BankCard.vue'
import BankCardDetail from '@/views/BankCardDetail.vue'
import AddBankCard from '@/views/AddBankCrad.vue'


import ApplyProduct from '@/views/product/applyProduct.vue'
import IdCard from '@/views/userCert/IdCard.vue'
import BaseInfo from '@/views/userCert/BaseInfo.vue'
import ContactPerson from '@/views/userCert/ContactPerson.vue'

const routes = [
    { path: '/', redirect: '/home' },
    { path: '/oauth2Authorize', component: Oauth2Authorize },
    { path: '/home', component: Home },
    { path: '/course', component: Course },
    { path: '/profile', component: Profile },
    { path: '/profile/complain', component: Complain },
    { path: '/profile/complain/addComplain', component: AddComplain },
    { path: '/profile/bankCard', component: BankCard },
    { path: '/profile/bankCardDetail', component: BankCardDetail },
    { path: '/profile/bankCard/AddBankCard', component: AddBankCard },

    { path: '/product/applyProduct', component: ApplyProduct },
    { path: '/userCert/idCard', component: IdCard },
    { path: '/userCert/baseInfo', component: BaseInfo },
    { path: '/userCert/contactPerson', component: ContactPerson },
]

const router = createRouter({
    history: createWebHistory(), // 使用 history 模式
    routes
})

let redirected = false;

router.beforeEach((to, from, next) => {
    if (!redirected && to.query.redirect) {
        redirected = true;
        const target = decodeURIComponent(to.query.redirect);

        // 使用 router.replace 跳转，同时去掉原来的 redirect query
        next({
            path: target.split('?')[0], // 路径
            query: Object.fromEntries(new URLSearchParams(target.split('?')[1] || '')), // token 等参数
            replace: true
        });
    } else {
        next();
    }
});



export default router
